package com.meichis.yndms.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.google.gson.Gson;
import com.meichis.mcsappframework.encrypt.AESProvider;
import com.meichis.mcsappframework.utils.DateUtil;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.Tools;
import com.meichis.yndms.R;
import com.meichis.yndms.adapter.VSTTemplateAdapter;
import com.meichis.yndms.common.MCode;
import com.meichis.yndms.databinding.ActivityVisitTemplateBinding;
import com.meichis.yndms.model.*;
import com.meichis.yndms.room.AppDatabase;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.VstTemplateVM;

import java.util.List;

public class VST_TemplateActivity extends BaseActivity {

    private VSTTemplateAdapter adapter;
    private Intent intent;
    private int curPosition;
    private static final int REQUEST_1 = 1001;


    private ActivityVisitTemplateBinding binding;
    private VstTemplateVM vm;

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_visit_template);
        vm = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(VstTemplateVM.class);
        binding.setVm(vm);
        binding.setClick(new ClickEvent());
        binding.setLifecycleOwner(this);
    }

    @Override
    protected void init() {
        binding.navigation.txtTitle.setText("门店拜访");
        binding.navigation.navBack.setOnClickListener(v -> onBackPressed());
        intent = getIntent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        vm.setClientInfo((ClientInfo) getIntent().getSerializableExtra(MCode.CLIENT));
        vm.getVisitWork(vm.getClientInfo().getID());
        vm.setShopInfo((ShopInfo) getIntent().getSerializableExtra(MCode.ShopInfo));

        addObserver();
    }


    private void addObserver() {
        vm.getShowDialog().observe(this, aBoolean -> showLoading(aBoolean));

        vm.getIsSyncVstTemplate().observe(this, aBoolean -> {
            if (aBoolean) {
                vm.getTemplate();
            }
        });

        vm.getTemplate().observe(this, template -> {
            if (template == null) {
                if (template == null) {
                    if (vm.syncCount > 1) {
                        MessageTools.showLongToast("多次同步未获取到拜访模版");
                        return;
                    }
                    MessageTools.ShowmessageDialog(VST_TemplateActivity.this, "未获取到拜访模版，请同步模版数据后再试", (dialogInterface, i) -> {
                        showLoading("模版数据同步中", false);
                        vm.syncCount++;
                        vm.GetVisitTemplateList();
                    }, (dialogInterface, i) -> close());
                    return;
                }
            }

            adapter = new VSTTemplateAdapter(this, R.layout.activity_vst_template_item, template.getItems());
            binding.lvTemplate.setAdapter(adapter);

            binding.lvTemplate.setOnItemClickListener((parent, view, position, id) -> {
                if (vm.getWork().getValue() != null) {
                    intent.putExtra(MCode.VISITGUID, vm.getWork().getValue().getGUID());
                    if (template.getIsMustSequenceCall() && !checkIsSequence(template.getItems().get(position).getSortID())) {
                        return;
                    }
                } else if (!"JD".equals(template.getItems().get(position).getProcess().getCode())) {
                    showMsg("请先执行【" + template.getItems().get(0).getProcess().getName() + "】环节，开始拜访");
                    return;
                }
                intent.putExtra(MCode.CODE, template.getItems().get(position).getProcess().getCode());
                intent.putExtra("Name", template.getItems().get(position).getProcess().getName());
                if (!TextUtils.isEmpty(template.getItems().get(position).getProcess().getActivityName())) {
                    try {
                        if ("YNDI_Questionnaire".equals(template.getItems().get(position).getProcess().getCode())) {
                            intent.setClass(VST_TemplateActivity.this, Class.forName("com.meichis.yndms.ui.activity." + "VST_FreeQuestionnaireListActivity"));
                        } else {
                            intent.setClass(VST_TemplateActivity.this, Class.forName("com.meichis.yndms.ui.activity." + template.getItems().get(position).getProcess().getActivityName()));
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        showMsg("当前版本暂不支持此模块！");
                        return;
                    }
                } else {
                    showMsg("当前版本暂不支持此模块!");
                }
                if (!TextUtils.isEmpty(template.getItems().get(position).getProcess().getActivityParams())) {
                    intent.putExtra("Params", template.getItems().get(position).getProcess().getActivityParams());
                }
                if (template.getItems().get(position).getProcess().getInspectTemplate() != null) {
                    intent.putExtra("InspectTemplate", template.getItems().get(position).getProcess().getInspectTemplate());
                }

                curPosition = position;

                switch (template.getItems().get(position).getProcess().getCode()) {
                    case "JD":
                        if (Tools.isConnected(VST_TemplateActivity.this)) {
                            intent.putExtra("VisitTemplate", template);
                            startActivityForResult(intent, 0);
                        } else {
                            showMsg("暂无网络连接，请检查网络！");
                        }
                        return;
                    case "LD":
                        if (Tools.isConnected(VST_TemplateActivity.this)) {
                            if (!checkprocess(true)) {
                                return;
                            }
                            intent.putExtra("VisitTemplate", template);
                        } else {
                            showMsg("暂无网络连接，请检查网络！");
                        }
                        break;

                    default:
                        break;
                }
                startActivityForResult(intent, REQUEST_1);
            });
        });

    }


    private boolean checkIsSequence(int SortID) {
        for (VisitTemplateDetail m : vm.getTemplate().getValue().getItems()) {
            if (m.getSortID() < SortID && !m.isCanSkip() && !m.isExec()) {
                showMsg("【" + m.getProcess().getName() + "】不可跳过");
                return false;
            }
        }
        return true;
    }


    @Override
    public void onBackPressed() {
        if (vm.getWork().getValue() == null) {
            super.onBackPressed();
            return;
        }

        if (!checkprocess(false)) {
            return;
        }
        MessageTools.ShowmessageDialog(this, "是否完成拜访?", (dialog, which) -> {
            if (!Tools.isConnected(VST_TemplateActivity.this)) {
                showMsg("暂无网络连接，请检查网络！");
                return;
            }
            EndWork();
        });
    }

    private boolean checkprocess(boolean ld) {
        for (VisitTemplateDetail m : vm.getTemplate().getValue().getItems()) {
            if (!m.isCanSkip() && !m.isExec()) {
                if (!ld || !"LD".equals(m.getProcess().getCode())) {
                    showMsg("请完成【" + m.getProcess().getName() + "】再结束拜访");
                    return false;
                }
            }
        }
        return true;
    }

    private void EndWork() {
        VisitWorkItem LDitem = new VisitWorkItem();
        LDitem.setProcessCode("LD");
        LDitem.setVisitGUID(vm.getWork().getValue().getGUID());
        LDitem.setWorkTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
        LDitem.setEndTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
        VisitWorkItem_JD ld = new VisitWorkItem_JD();
        ld.setJobType(2);
        ld.setJudgeMode(1);
        LDitem.setJD(ld);
        AppDatabase.getInstance().visitWorkItemDao().insert(LDitem);
        vm.getWork().getValue().setEndTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
        List<VisitWorkItem> items = AppDatabase.getInstance().visitWorkItemDao().findAll(vm.getWork().getValue().getGUID());
        vm.getWork().getValue().getItems().clear();
        vm.getWork().getValue().getItems().addAll(items);
        vm.getWork().getValue().setIsComplete(true);
        AppDatabase.getInstance().visitWorkDao().update(vm.getWork().getValue());

        AppDatabase.getInstance().visitWorkItemDao().deleteAll(vm.getWork().getValue().getGUID());
        AppDatabase.getInstance().visitWorkDao().delete(vm.getWork().getValue());
        setResult(Activity.RESULT_OK);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            vm.getTemplate().getValue().getItems().get(curPosition).setExec(true);//点击*消失
            adapter.notifyDataSetChanged();
        }
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public class ClickEvent {
        public void onTelAction() {
            //跳转到拨号界面，同时传递电话号码
            String tel = vm.getShopInfo().getMobile().contains("+86") ?
                    vm.getShopInfo().getMobile().replace("+86", "")
                    : vm.getShopInfo().getMobile();
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
            startActivity(intent);
        }
    }
}